import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { RolePermissionDto } from './dto/role-permission.dto';
import { RolePermissionEntity } from './entity/role-permission.entity';
import * as uuid from 'uuid';
@Injectable()
export class RolePermissionService {
  constructor(
    @InjectRepository(RolePermissionEntity)
    private readonly rolePermissionRepository: Repository<RolePermissionEntity>,
  ) {}

  // 关联角色和菜单权限数据
  async create(rolePermission: RolePermissionDto) {
    const { role_id, permission_id } = rolePermission;
    let permissionArray = []; // 新添加菜单权限数据
    if (typeof permission_id != 'string') {
      throw new NotFoundException(
        'permission_id参数格式应为英文逗号分割的字符串',
      );
    } else {
      permissionArray = permission_id.split(',');
    }

    const querySql = `select id,role_id,permission_id FROM sys_role_permission`;
    const queryResult = await this.rolePermissionRepository.query(querySql);
    // 如果角色关联菜单数量大于0则清空后添加
    if (queryResult.length > 0) {
      const deleteSql = `DELETE FROM sys_role_permission WHERE role_id='${role_id}'`;
      await this.rolePermissionRepository.query(deleteSql);
    }
    /* 批量新增数据
    insert into table_name (column1,column2,column3...) values
    (value1,value2,value3...),(value1,value2,value3...),(value1,value2,value3...)
    */
    const saveFirst = `insert into sys_role_permission (id,role_id,permission_id) values`;
    let saveLast = '';
    for (let i = 0; i < permissionArray.length; i++) {
      const element = permissionArray[i];
      const createId = uuid.v4().replace(/-/g, '');
      saveLast += ` ('${createId}','${role_id}','${element}'),`;
    }
    let saveSql = saveFirst + saveLast;
    saveSql = saveSql.replace(/,$/gi, '');

    return await this.rolePermissionRepository.query(saveSql);
    // return await this.rolePermissionRepository.save(rolePermission);
  }

  // 获取角色已经关联权限菜单id
  async queryRoleById(query) {
    const { id } = query;
    const sql = `select permission_id FROM sys_role_permission WHERE role_id='${id}'`;
    const data = await this.rolePermissionRepository.query(sql);
    const result = [];
    for (let i = 0; i < data.length; i++) {
      const element = data[i];
      result.push(element.permission_id);
    }
    return { result: result };
  }
}
